<template>
  <div :class="['tr-checkboxgroup-big', 'no-outline', styles.module]">
    <LabelPrefixWrapper
      v-show="mappingProps.visible"
      :class="['tr-checkbox-group', 'no-outline', styles.module]"
      :required="mappingProps.required"
      :label="mappingProps.label"
      :hideLabel="mappingProps.hideLabel"
      :labelPosition="mappingProps.labelPosition"
      :helpConf="mappingProps.helpConf"
      :helpTooltip="mappingProps.helpTooltip"
      :helpPlacement="mappingProps.helpPlacement"
      :helpMore="mappingProps.helpMore"
      :helpMorePopup="mappingProps.helpMorePopup"
      :helpMoreLink="mappingProps.helpMoreLink"
      :helpMoreLinkHrefStatic="mappingProps.helpMoreLinkHrefStatic"
      :helpMoreLinkHrefExp="mappingProps.helpMoreLinkHrefExp"
      :readonly="mappingProps.readonly"
    >
      <div style="width: 100%; flex: 1; position: relative">
        <div class="tr-checkbox-group-div no-outline">
          <Component
            v-bind="{ ...attrs_, ...mappingProps }"
            :class="['tr-checkbox-group-small', 'no-outline', styles.module]"
            :disable="mappingProps.readonly"
            :label="undefined"
            :size="mappingProps.size"
            @update:model-value="showChannel()"
            color="var(--t-color)"
            :options="
              mappingProps.itemsDataSourceType === ''
                ? mappingProps.options
                : mappingProps.itemsDataSourceType === 'static'
                  ? computedStaticItems(mappingProps.staticItems)
                  : computedDynamicList
            "
            type="checkbox"
          >
            <template v-for="(v, k, a) in $slots" v-slot:[k]>
              <slot :name="k" />
            </template>
          </Component>
          <div
            :class="{
              'message-checkbox-bg': displayedRequiredError,
              'tr-checkbox-group-div-bg': true,
            }"
            style="height: 1px"
          ></div>
        </div>
        <div v-if="displayedRequiredError" class="u-error-message">
          {{ mappingProps.requiredMessage }}
        </div>
      </div>
    </LabelPrefixWrapper>
  </div>
</template>

<script>
import Component from '@teld/q-components/OptionGroup';
import useMappingProps from 't/common/hooks/useMappingProps';
import { commonProps, createNameSpace } from 't/common/utils';
import { computed, defineComponent, ref, watchEffect } from 'vue';
import LabelPrefixWrapper from '../label-prefix-wraper';
import styles from './index.module.scss';
import './index.scss';
// 钩子方法
import { useFormChild } from '@teld/q-components';
import { useI18n } from 'vue-i18n';
import label from '../label';

export default defineComponent({
  name: createNameSpace('checkbox-group'),
  components: { Component, LabelPrefixWrapper },
  props: {
    ...commonProps,
    ...Component.props,
    ...LabelPrefixWrapper.props,
    readonly: Boolean,
    itemsDataSourceType: {
      type: String,
      default() {
        return '';
      },
    },
    size: {
      type: String,
      default() {
        return 'xs';
      },
    },
    required: {
      type: Boolean,
      default() {
        return false;
      },
    },
    requiredMessage: {
      type: String,
      default() {
        return '必填不能为空';
      },
    },
    listDataSource: Array,
    staticItems: Array,
    displayField: String,
    valueField: String,
    modelValue: {
      type: Array,
      default() {
        return [];
      },
    },
    mockValue: {
      type: String,
      default() {
        return '';
      },
    },
  },

  emits: ['change'],
  setup(props, { attrs, emit, expose, slots }) {
    const { t } = useI18n({ useScope: 'global' });
    let attrs_ = { ...attrs };
    delete attrs_['data-uid'];
    delete attrs_['data-tag'];
    delete attrs_['class'];
    delete attrs_['style'];
    const [mappingProps, mappingExpose] = useMappingProps(props);
    expose({ ...mappingExpose, validate });
    const computedDynamicList = computed(() => {
      if (!!window['fas']?.inDesign) {
        return mappingProps.mockValue &&
          typeof mappingProps.mockValue == 'string'
          ? JSON.parse(mappingProps.mockValue)
          : [
              {
                ID: 'fasr_checkboxgroup.StaticItems.Item1',
                label: '静态数据1',
                value: 1,
                ValueInfo_label:
                  'Schema.Controls.fasr_checkboxgroup.StaticItems.Item1.label',
              },
              {
                ID: 'fasr_checkboxgroup.StaticItems.Item2',
                label: '静态数据2',
                value: 2,
                ValueInfo_label:
                  'Schema.Controls.fasr_checkboxgroup.StaticItems.Item2.label',
              },
            ];
      } else {
        let list = mappingProps.listDataSource;
        if (!(list instanceof Array))
          return [
            {
              [mappingProps.displayField]: '动态数据源',
              [mappingProps.valueField]: '',
            },
          ];
        if (list.length == 0) {
          list = [
            {
              [mappingProps.displayField]: '动态数据源',
              [mappingProps.valueField]: '',
            },
          ];
        }
        return list.map(item => {
          const obj = {
            label: item[mappingProps.displayField],
            value: item[mappingProps.valueField],
          };
          return { ...item, ...obj };
        });
      }
    });
    const computedStaticItems = list => {
      if (list) {
        return list.map(item => {
          return { ...item, label: t(item.ValueInfo_label || '', item.label) };
        });
      }
    };
    function showChannel() {
      emit('change');
    }
    // ============================= 必填校验相关 ===========================
    // 是否显示必填校验错误
    const displayedRequiredError = ref(false);

    // 必填校验
    function validate() {
      const { required, modelValue, requiredMessage } = mappingProps;
      const value = modelValue;
      displayedRequiredError.value =
        required && Array.isArray(value) && value.length === 0;
      return !displayedRequiredError.value;
    }
    // 与qForm组件通信，校验用户输入是否合法
    useFormChild({
      validate, // 函数；可以是异步的；
      // 应该返回一个布尔值（或一个 resolve 布尔值的 Promise）
      resetValidation() {
        displayedRequiredError.value = false;
      }, // 可选的函数，可重置验证
      requiresQForm: false, // 如果没有找到父级 QForm，它是否应该报错？
    });
    // 评分改变回调
    watchEffect(() => {
      // const value = mappingProps.modelValue;
      // emit('update:modelValue', value)
      // 如果已经报了必填错误，更改时校验下
      if (displayedRequiredError.value) validate();
    });
    return {
      attrs_,
      styles,
      mappingProps,
      showChannel,
      validate,
      displayedRequiredError,
      computedDynamicList,
      computedStaticItems,
    };
  },
});
</script>

<style lang="scss">
.tr-checkbox-group {
  // 错误提示样式和input组件保持一致
  .u-error-message {
    padding-top: 5px;
    font-size: 12px;
    line-height: 1.5;
    color: #ff0000;
    word-break: break-word;
    word-wrap: break-word;
    overflow-wrap: break-word;
    min-width: 90px;
  }
}
@media only screen and (max-width: 767px) {
  .message-checkbox-bg {
    background-color: #ff5a66 !important;
  }
}
</style>
